<?php
namespace App\Http\Controllers;
use App\Common\ResponseCode;

/**
 * 基础控制器
 *
 * @author WangBin
 * @date 2021-06/11
 * @package App\Http\Controllers\H5
 */
class BaseController extends Controller
{
    /**
     * 统一返回结果处理
     *
     * @param $responseCode
     * @param null $data
     * @param array $extend
     * @return \Illuminate\Http\JsonResponse
     */
    protected function codeReturn($responseCode, $data = null, array $extend = [])
    {
        list($errno, $errmsg) = $responseCode;
        $ret = ['error_code' => $errno, 'error_msg' => $errmsg];
        // 附加的信息
        if(!empty($extend)) {
            $field = array_keys($extend)[0];
            $ret['error_msg'] = str_replace( '%' . $field, ',' . $extend[$field], $ret['error_msg']);
        } else {
            $ret['error_msg'] = preg_replace("/%[a-z]+/", '', $ret['error_msg']);
        }
        if(!is_null($data)) {
            $ret['data'] = $data;
        }
        return response()->json($ret);
    }

    /**
     * 返回成功结果
     *
     * @param null $data
     * @return \Illuminate\Http\JsonResponse
     */
    protected function success($data = null)
    {
        return $this->codeReturn(ResponseCode::SUCCESS, $data);
    }

    /**
     * 返回失败结果
     *
     * @param array $responseCode
     * @param array $extend
     * @return \Illuminate\Http\JsonResponse
     */
    protected function fail(array $responseCode, array $extend = [])
    {
        return $this->codeReturn($responseCode, null, $extend);
    }
}
